package org.anyin.gitee.cloud.center.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.anyin.gitee.cloud.center.common.constants.CommonConstants;
import org.anyin.gitee.cloud.center.common.constants.GatewayConstants;
import org.anyin.gitee.cloud.lib.core.utils.RequestIdUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
* 生成request id
* @author         xyz
* @since          2021/10/23
*/
@Slf4j
public class GatewayRequestIdFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        RequestIdUtil.generateRequestId();
        log.info("request uri: {}, request id: {}", exchange.getRequest().getURI().getPath(), RequestIdUtil.getRequestId().toString());
        exchange.getAttributes().put(CommonConstants.REQUEST_ID, RequestIdUtil.getRequestId().toString());
        ServerWebExchange newExchange = this.setHeaderRequestId(exchange, RequestIdUtil.getRequestId().toString());
        try {
            return chain.filter(newExchange);
        }finally {
            RequestIdUtil.removeRequestId();
        }
    }

    private ServerWebExchange setHeaderRequestId(ServerWebExchange exchange, String requestId) {
        ServerHttpRequest request = exchange.getRequest().mutate().header(CommonConstants.REQUEST_ID, new String[]{requestId}).build();
        return exchange.mutate().request(request).build();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
